package com.shiehub.sdk.opengw.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ShieTcpUtil {

  public static String sendTcp(String url, String xml) throws Exception {

    OutputStream os = null;
    ByteArrayInputStream bais = null;
    ByteArrayOutputStream baos = null;
    InputStream is = null;
    try {
      String ip = url.split(":")[0];
      int port = Integer.parseInt(url.split(":")[1]);
      Socket socket = new Socket(ip, port);
      socket.setSoTimeout(10000);
      //发送信息
      os = socket.getOutputStream();
      bais = new ByteArrayInputStream(xml.getBytes("UTF-8"));
      int inLen = 0;
      byte[] inBuf = new byte[1024];
      while ((inLen = bais.read(inBuf)) != -1) {
        os.write(inBuf, 0, inLen);
      }
      os.flush();

      //接收信息
      is = socket.getInputStream();
      baos = new ByteArrayOutputStream();
      int len = 0;
      byte[] buf = new byte[1024];
      while ((len = is.read(buf)) != -1) {
        baos.write(buf, 0, len);
      }
      os.close();

    } catch (Exception e) {

      throw e;
    }

    return new String(baos.toByteArray());
  }
}
